package top.yangbuyi.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yangbuyi.system.common.ActiveUser;
import top.yangbuyi.system.common.Constant;
import top.yangbuyi.system.common.MD5Utils;
import top.yangbuyi.system.common.WebUtils;
import top.yangbuyi.system.config.GITEE.GiteeDTO;
import top.yangbuyi.system.config.QQ.OAuthProperties;
import top.yangbuyi.system.domain.Loginfo;
import top.yangbuyi.system.domain.User;
import top.yangbuyi.system.service.LoginfoService;
import top.yangbuyi.system.service.UserService;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * description:  杨不易网站 :www.yangbuyi.top
 * program:  yangbuyi-erp-2020
 * ClassName:  GiteeController
 * create:  2020-07-02 09:44
 *
 * @author: yangbuyi
 * @since： JDK1.8
 **/

@RestController
@RequestMapping("api/gitee")
public class GiteeController {
      
      @Autowired
      private UserService userService;
      @Autowired
      private LoginfoService loginfoService;
      private static final Logger logger = LoggerFactory.getLogger(GiteeController.class);
      @Autowired
      private OAuthProperties qqProperties;
      
   
      
      @RequestMapping("/oautn2")
      public void oautn2(String code, HttpServletResponse response) throws Exception {
            System.out.println("得到的code为：" + code);
            Map<String, String> params = new LinkedHashMap<>(5);
            
            String url = "https://gitee.com/oauth/token";
            //申请应用时分配的AppKey
            params.put("client_id", "0c4e58561c42d8af62c151e48c3f8702287ef88194721992b24af3edd3312791");
            //申请应用时分配的AppSecret
            params.put("client_secret", "fa8da266a1d39e2ffe139982fd9281826ebb59eeaf2bbba4703a6f6bbe8f358a");
            //请求的类型，填写authorization_code
            params.put("grant_type", "authorization_code");
            //调用authorize获得的code值
            params.put("code", code);
            //回调地址，需需与注册应用里的回调地址一致。
            params.put("redirect_uri", "https://www.yangbuyi.top/api/gitee/oautn2");
            
            // 定义token
            String token = "";
            try {
                  String result = top.yangbuyi.system.common.HttpUtil.post(url, params);
                  System.out.println("得到的结果为：" + result);
                  
                  JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
                  url = "https://gitee.com/api/v5/user";
                  String getUserInfo = top.yangbuyi.system.common.HttpUtil.get(url, jsonObject.get("access_token"));
                  System.out.println("得到的用户信息为：" + getUserInfo);
                  jsonObject = (JSONObject) JSONObject.parse(getUserInfo);
//                  model.addAttribute("userName", jsonObject.get("name"));
//                  model.addAttribute("userImage", jsonObject.get("avatar_url"));
                  
                  
                  // 强制转换
                  GiteeDTO giteeDTO = (GiteeDTO) JSON.parseObject(getUserInfo,GiteeDTO.class);
                  
                  
                  // 这里进行 QQ登陆用户 添加新的用户
                  // 设置用户基本信息
                //  GiteeDTO giteeDTO = new GiteeDTO();
                  
                  User user1 = this.userService.queryUserByLoginName((String) jsonObject.get("login"));
                  User user = null;
                  String remoteAddr1 = WebUtils.getHttpServletRequest().getHeader("X-Forwarded-For");
                  if (user1 == null) {
                        user = new User();
                        user.setName((String) jsonObject.get("name"));
                        user.setLoginname((String) jsonObject.get("login"));
                        user.setSalt(MD5Utils.createUUID());
                        user.setType(Constant.USER_TYPE_NORMAL);
                        user.setPwd(MD5Utils.md5(Constant.DEFAULT_PWD, user.getSalt(), 2));
                        user.setSex(0);
                        user.setAvailable(Constant.AVAILABLE_TRUE);
                        user.setImgpath((String) jsonObject.get("avatar_url"));
                        user.setRemark("GITEE登陆-" + jsonObject.get("name"));
                        user.setAddress("GITEE登陆 - IP地址" + remoteAddr1);
                        user.setDeptid(46);
                        user.setHiredate(new Date());
                        user.setOrdernum(this.userService.queryUserMaxOrderNum() + 1);
                        // 进行保存用户
                        this.userService.saveUser(user);
                        
                        
                        // 设置默认的角色
                        User user2 = this.userService.queryUserByLoginName(user.getLoginname());
                        /**
                         * 保存角色
                         */
                        this.userService.saveUserRole(user2.getId(), Constant.QQ_ROLE_DEFAULT);
                        System.out.println(user);
                        
                  }else{
                        // 修改gitee
                        // 如果已经有用户了  重新录入头像
                        user1.setName((String) jsonObject.get("name"));
                        user1.setLoginname((String) jsonObject.get("login"));
                        user1.setSex(0);
                        user1.setAvailable(Constant.AVAILABLE_TRUE);
                        user1.setImgpath((String) jsonObject.get("avatar_url"));
                        user1.setRemark("GITEE登陆-" + jsonObject.get("name"));
                        user1.setAddress("GITEE登陆 - IP地址" + remoteAddr1);
                        this.userService.updateUser(user1);
                        
                  }
                  
                  // 获取主体
                  Subject subject = SecurityUtils.getSubject();
//                  SecurityUtils.getSubject().login(new UsernamePasswordToken(qqOpenidDTO.getOpenid(), Constant.DEFAULT_PWD));
                  
                  
                  // 进行Shiro认证
                  subject.login(new UsernamePasswordToken(giteeDTO.getLogin(), Constant.DEFAULT_PWD));
                  
                  token = subject.getSession().getId().toString();
                  ActiveUser active = (ActiveUser) subject.getPrincipal();
                  
                  /* 写入登陆日志开始 */
                  Loginfo loginfo = new Loginfo();
                  // String remoteAddr = WebUtils.getHttpServletRequest().getHeader("X-Forwarded-For");
                  loginfo.setLoginip(remoteAddr1);
                  loginfo.setLoginname(giteeDTO.getLogin());
                  loginfo.setLogintime(new Date());
                  loginfoService.save(loginfo);
                  /* 写入登陆日志结束 */
                  params.put("token", token);
                  logger.info("执行GITEE登陆全部结束认证成功完毕");
                  System.out.println("Shiro认证成功");
                  WebUtils.getHttpSession().setAttribute("params", params);
                  System.out.println(token);
                  
                  
                  response.sendRedirect(qqProperties.getQQ().getRedirect_url_index_yby() + "?token=" + token + "&gitee=" + giteeDTO);
                  // return "成功" + getUserInfo;
            } catch (Exception e) {
                  e.printStackTrace();
                  response.sendRedirect(qqProperties.getQQ().getRedirect_url_login_yby());
            }
            //  return "失败";
      }
      
      
}
